#Boa:Dialog:Dialog1

import wx
import wx.grid
import consultasBD
import Mensaje
import sincronizar_tabla  
import utiles

def create(parent):
    return Dialog1(parent)

[wxID_DIALOG1, wxID_DIALOG1BUTTON1, wxID_DIALOG1BUTTON2, wxID_DIALOG1CANTIDAD, 
 wxID_DIALOG1GRID1, wxID_DIALOG1OBSERVACION, wxID_DIALOG1PTC, 
 wxID_DIALOG1SIGNO, wxID_DIALOG1STATICTEXT1, wxID_DIALOG1STATICTEXT10, 
 wxID_DIALOG1STATICTEXT11, wxID_DIALOG1STATICTEXT12, wxID_DIALOG1STATICTEXT13, 
 wxID_DIALOG1STATICTEXT14, wxID_DIALOG1STATICTEXT15, wxID_DIALOG1STATICTEXT16, 
 wxID_DIALOG1STATICTEXT2, wxID_DIALOG1STATICTEXT3, wxID_DIALOG1STATICTEXT4, 
 wxID_DIALOG1STATICTEXT5, wxID_DIALOG1STATICTEXT6, wxID_DIALOG1STATICTEXT7, 
 wxID_DIALOG1STATICTEXT8, wxID_DIALOG1STATICTEXT9, wxID_DIALOG1TIPO_AJUSTE, 
] = [wx.NewId() for _init_ctrls in range(25)]

class Dialog1(wx.Dialog):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self, id=wxID_DIALOG1, name='', parent=prnt,
              pos=wx.Point(391, 257), size=wx.Size(794, 229),
              style=wx.DEFAULT_DIALOG_STYLE, title='Ajustes')
        self.SetClientSize(wx.Size(786, 202))
        self.Show(False)
        self.SetHelpText(u'')
        self.SetToolTipString(u'Dialog1')

        self.staticText1 = wx.StaticText(id=wxID_DIALOG1STATICTEXT1,
              label=u'PTC', name='staticText1', parent=self, pos=wx.Point(16,
              8), size=wx.Size(28, 16), style=0)

        self.staticText2 = wx.StaticText(id=wxID_DIALOG1STATICTEXT2,
              label='Cantidad', name='staticText2', parent=self,
              pos=wx.Point(104, 8), size=wx.Size(43, 13), style=0)

        self.staticText3 = wx.StaticText(id=wxID_DIALOG1STATICTEXT3, label=u'',
              name='staticText3', parent=self, pos=wx.Point(112, 314),
              size=wx.Size(387, 18), style=0)

        self.staticText5 = wx.StaticText(id=wxID_DIALOG1STATICTEXT5,
              label=u'Tipo de Ajuste', name='staticText5', parent=self,
              pos=wx.Point(232, 8), size=wx.Size(104, 16), style=0)

        self.staticText6 = wx.StaticText(id=wxID_DIALOG1STATICTEXT6,
              label='Observaciones', name='staticText6', parent=self,
              pos=wx.Point(336, 8), size=wx.Size(71, 13), style=0)

        self.ptc = wx.TextCtrl(id=wxID_DIALOG1PTC, name=u'ptc', parent=self,
              pos=wx.Point(16, 24), size=wx.Size(80, 24), style=0, value=u'')
        self.ptc.Bind(wx.EVT_KILL_FOCUS, self.OnPtcKillFocus)

        self.cantidad = wx.TextCtrl(id=wxID_DIALOG1CANTIDAD, name=u'cantidad',
              parent=self, pos=wx.Point(104, 24), size=wx.Size(40, 24), style=0,
              value=u'')

        self.signo = wx.Choice(choices=['positivo', 'negativo'],
              id=wxID_DIALOG1SIGNO, name=u'signo', parent=self,
              pos=wx.Point(145, 24), size=wx.Size(80, 21), style=0)

        self.tipo_ajuste = wx.Choice(choices=['generico', 'discrepancia'],
              id=wxID_DIALOG1TIPO_AJUSTE, name=u'tipo_ajuste', parent=self,
              pos=wx.Point(232, 24), size=wx.Size(96, 21), style=0)

        self.observacion = wx.TextCtrl(id=wxID_DIALOG1OBSERVACION,
              name=u'observacion', parent=self, pos=wx.Point(336, 24),
              size=wx.Size(440, 24), style=0, value=u'')

        self.button1 = wx.Button(id=wxID_DIALOG1BUTTON1, label=u'Guardar',
              name='button1', parent=self, pos=wx.Point(608, 168),
              size=wx.Size(80, 24), style=0)
        self.button1.Bind(wx.EVT_BUTTON, self.OnGuardar, id=wxID_DIALOG1BUTTON1)

        self.button2 = wx.Button(id=wxID_DIALOG1BUTTON2, label='Cerrar',
              name='button2', parent=self, pos=wx.Point(696, 168),
              size=wx.Size(80, 24), style=0)
        self.button2.Bind(wx.EVT_BUTTON, self.OnBotonCerrar,
              id=wxID_DIALOG1BUTTON2)

        self.staticText7 = wx.StaticText(id=wxID_DIALOG1STATICTEXT7,
              label='Stock en sucursales', name='staticText7', parent=self,
              pos=wx.Point(336, 56), size=wx.Size(112, 13), style=0)
        self.staticText7.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              'Tahoma'))

        self.grid1 = wx.grid.Grid(id=wxID_DIALOG1GRID1, name='grid1',
              parent=self, pos=wx.Point(336, 72), size=wx.Size(440, 80),
              style=0)

        self.staticText4 = wx.StaticText(id=wxID_DIALOG1STATICTEXT4, label='',
              name='staticText4', parent=self, pos=wx.Point(16, 72),
              size=wx.Size(312, 13), style=0)

        self.staticText8 = wx.StaticText(id=wxID_DIALOG1STATICTEXT8, label='',
              name='staticText8', parent=self, pos=wx.Point(72, 96),
              size=wx.Size(56, 13), style=0)

        self.staticText9 = wx.StaticText(id=wxID_DIALOG1STATICTEXT9, label='',
              name='staticText9', parent=self, pos=wx.Point(16, 136),
              size=wx.Size(312, 13), style=0)

        self.staticText10 = wx.StaticText(id=wxID_DIALOG1STATICTEXT10,
              label='Descripcion', name='staticText10', parent=self,
              pos=wx.Point(16, 56), size=wx.Size(65, 13), style=0)
        self.staticText10.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD,
              False, 'Tahoma'))

        self.staticText11 = wx.StaticText(id=wxID_DIALOG1STATICTEXT11,
              label='Precio $', name='staticText11', parent=self,
              pos=wx.Point(16, 96), size=wx.Size(45, 13), style=0)
        self.staticText11.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD,
              False, 'Tahoma'))

        self.staticText12 = wx.StaticText(id=wxID_DIALOG1STATICTEXT12,
              label='Proveedor', name='staticText12', parent=self,
              pos=wx.Point(16, 120), size=wx.Size(59, 13), style=0)
        self.staticText12.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD,
              False, 'Tahoma'))

        self.staticText13 = wx.StaticText(id=wxID_DIALOG1STATICTEXT13,
              label='Talle', name='staticText13', parent=self, pos=wx.Point(16,
              152), size=wx.Size(27, 13), style=0)
        self.staticText13.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD,
              False, 'Tahoma'))

        self.staticText14 = wx.StaticText(id=wxID_DIALOG1STATICTEXT14,
              label='Color', name='staticText14', parent=self, pos=wx.Point(120,
              152), size=wx.Size(29, 13), style=0)
        self.staticText14.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD,
              False, 'Tahoma'))

        self.staticText15 = wx.StaticText(id=wxID_DIALOG1STATICTEXT15, label='',
              name='staticText15', parent=self, pos=wx.Point(16, 168),
              size=wx.Size(88, 13), style=0)

        self.staticText16 = wx.StaticText(id=wxID_DIALOG1STATICTEXT16, label='',
              name='staticText16', parent=self, pos=wx.Point(120, 168),
              size=wx.Size(208, 13), style=0)

    def __init__(self, parent):
        self._init_ctrls(parent)
        self.padre = parent
        self.sucursal = self.padre.sucursalNro
        self.creaGrilla()
        self.grid1.Show(False)
        self.staticText7.Show(False)
 
    def creaGrilla(self):
        consultaSQL = "SELECT * FROM sucursales WHERE 1"
        resultadoSUC = consultasBD.ordenCrudaDict(consultaSQL)
        columnas = len(resultadoSUC)
        self.grid1.CreateGrid(1,columnas)
        sucursales = []
        for i in xrange(columnas):
            cadena = resultadoSUC[i]['nombre']
            cadena = cadena.split()[0]+"\n"+cadena[cadena.find(" ")+1:]
            sucursales.append(cadena)
        for i in xrange(columnas):
            self.grid1.SetColLabelValue(i,sucursales[i])
            self.grid1.SetCellValue(0, i, "0")
            self.grid1.SetCellAlignment(0, i, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)                
        return

    def _validar(self, ptc, cantidad):
        if ptc == "":
            utiles.mensaje(self, "Debe ingresar un PTC")
            return False
        
        sql_ptc = "SELECT * FROM producto_talle_color WHERE id = '%s'" % ptc
        t = consultasBD.ordenCruda(sql_ptc)
        if not t:
            utiles.mensaje(self, "El PTC no fue encontrado")
            return False            
        
        try:
            t = int(cantidad)
            if t < 0:
                raise Exception()
        except ValueError:
            utiles.mensaje(self, "La cantidad debe ser un Numero")
            return False
        except Exception:
            utiles.mensaje(self, "La cantidad debe ser un Numero entero y positivo")
            return False
        
        return True

    def OnGuardar(self, event):
        ptc = self.ptc.Value
        cantidad = self.cantidad.Value
        signo = self.signo.GetStringSelection()
        tipo_ajuste = self.tipo_ajuste.GetStringSelection()        
        observacion = self.observacion.Value
        if not self._validar(ptc, cantidad):
            return
        
        cantidad = int(cantidad)
        
        try:
            consultasBD.begin()
            if signo == "negativo":
                cantidad *= -1
            operacion = "ajuste"
            if tipo_ajuste == "discrepancia":
                operacion = "ajuste_discrepancia"

            #Se registra el movimiento
            stock = utiles.stock_sumado(ptc, self.sucursal, cantidad)
            utiles.agregar_movimiento(ptc, stock_previo=stock - cantidad, stock_nuevo=stock, operacion=operacion, sucursal=self.sucursal, observacion=observacion)

            sql = "UPDATE stock SET stock = '%s' WHERE ptc = '%s' AND sucursal = '%s'" % (stock, ptc, self.sucursal)
            sincronizar_tabla.addChange(sql=sql)
            consultasBD.executaSinCommit(None, sql)

            consultasBD.commit()
            sincronizar_tabla.syncServerTables(self, ["productos", "producto_talle_color", "stock"])
            utiles.mensaje(self, "El ajuste se guardo y sincronizo correctamente")            
            utiles.mensaje(self, "El stock actual es de %s" % stock)

            self.ptc.SetValue("")
            self.cantidad.SetValue("")
            self.observacion.SetValue("")
            self.ptc.SetFocus()

        except sincronizar_tabla.SyncError:
            utiles.mensaje(self, "El ajuste se guardo \n pero no termino de transmitirse por favor realize un sincronizacion")
        except Exception, e:
            import traceback
            import sys
            exc_type, exc_value, exc_tb = sys.exc_info()
            traceback.print_exception(exc_type, exc_value, exc_tb)
            print e.__str__()
            utiles.mensaje(self, "NO se pudo guardar el ajuste")    
            consultasBD.rollback()

        self.grid1.Show(False)
        self.staticText7.Show(False)
        self.staticText4.SetLabel("")
        self.staticText8.SetLabel("")
        self.staticText9.SetLabel("")
        columnas = self.grid1.GetNumberCols()
        for i in xrange(columnas):
            self.grid1.SetCellValue(0, i, "0")

    def OnBotonCerrar(self, event):
        self.Close()

    def OnPtcKillFocus(self, event):
        if self.ptc.GetValue() != "":
            self.grid1.Show(True)
            self.staticText7.Show(True)
            consultaSQL = "SELECT * FROM stock WHERE ptc='"+self.ptc.GetValue()+"'"
            resultadoStock = consultasBD.ordenCruda(consultaSQL)
            consultaSQL = "SELECT * FROM producto_talle_color WHERE id='"+self.ptc.GetValue()+"'"
            resultadoPTC = consultasBD.ordenCrudaDict(consultaSQL)
            consultaSQL = "SELECT * FROM productos WHERE codsussan='"+resultadoPTC[0]['codsussan']+"'"
            resultadoDES = consultasBD.ordenCrudaDict(consultaSQL)
            consultaSQL = "SELECT * FROM proveedor WHERE idproveedor='"+resultadoDES[0]['proveedor']+"'"
            resultadoPRO = consultasBD.ordenCrudaDict(consultaSQL)
            self.staticText4.SetLabel(resultadoDES[0]['descri'])
            self.staticText8.SetLabel(str(resultadoDES[0]['preciolt1']))
            self.staticText9.SetLabel(resultadoPRO[0]['nombre'])
            consultaSQL = "SELECT * FROM colores WHERE idcolor='"+resultadoPTC[0]['color']+"'"
            resultadoCOL = consultasBD.ordenCrudaDict(consultaSQL)
            self.staticText15.SetLabel(resultadoPTC[0]['talle'])
            self.staticText16.SetLabel(resultadoCOL[0]['nombre'])
            for i,item in enumerate(resultadoStock):
                self.grid1.SetCellValue(0,item[2]-1,str(item[1]))
                self.grid1.SetCellAlignment(0, item[2]-1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)                
            for col in xrange(self.grid1.GetNumberCols()):
                self.grid1.AutoSizeColumn(col,True)
            self.grid1.Refresh()

